#include "global_var.h"
#include "parse_config.h"

/* time位于哪一列（第一列、第二列...） */
extern int debug_mod;
extern int time_column;

/** 
 * 作用：解析配置文件
 * 参数是ifstream类型，文件名是当前目录下ntc_config.conf
 * device_name可能是空字符串
 */
std::filesystem::path get_exe_dir(){
#ifdef _WIN32
    TCHAR buffer[MAX_PATH];
    GetModuleFileName(NULL, buffer, MAX_PATH);
    return fs::path(buffer).parent_path();
#else
    char result[PATH_MAX];
    ssize_t count = readlink("/proc/self/exe", result, sizeof(result) - 1);
    if (count != -1) {
        result[count] = '\0';
        return fs::path(result).parent_path();
    } else {
        perror("readlink() error");
        throw std::runtime_error("Failed to get executable path");
    }
#endif
}

void parse_config(std::vector<std::string>& ntcs, std::string& device_name){

    std::filesystem::path cur_exe_dir = get_exe_dir();
    std::filesystem::path conf_dir_name("config_file");
    std::filesystem::path conf_dir = cur_exe_dir/conf_dir_name;
    std::filesystem::path conf_filename = device_name+"_ntc_config.conf";

    std::filesystem::path conf_file_path = conf_dir/conf_filename;
    std::string config_file_path = conf_file_path.string();
    if (debug_mod == 1){
        std::cout <<"cur_exe_dir:       "<<cur_exe_dir.string()<<std::endl
                  <<"device_name:       "<<device_name<<std::endl
                  <<"conf_filename:     "<<conf_file_path.string()<<std::endl
                  <<"config_file_path:  "<<config_file_path<<std::endl;
    }

    FILE* file_exist=fopen(config_file_path.c_str(), "r");

	// 不存在则将device_name重置为空字符串即可
	if(file_exist==nullptr){
		device_name="default";
        std::cout<<"device name u input not exist, use default config file."<<std::endl;
	}
	// 文件存在，只需关闭文件即可
	else{
        std::cout<<"use "<<device_name<<" config"<<std::endl;
		fclose(file_exist);
	}

	// 这里写相对路径在其他文件夹下执行时会报错
    std::ifstream conf_file(config_file_path);
	std::string line;

	// todo: 此处要将固定的几个属性加入默认通用配置
	// 放入固定需要解析的字段（这块也可拆出一个配置文件）
	ntcs.push_back("time");
	time_column=ntcs.size();
	ntcs.push_back("scenario");
	
	while(getline(conf_file,line)){
		if(line[0]=='#' || line.size()==0){
			continue;
		}
		while(line[0]=='[' || line[0]==']'){
			line.erase(0,1);
		}
		ntcs.push_back(line);
	}
	conf_file.close();
}
